/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
<template>
  <div>
    <s-header></s-header>
    <div>
      <img class="common-img" :src="goods.squarePic" />
      <div class="goods-info">
        <div class="goods-price">
          <span>¥{{ goods.price / 100 }}</span>
        </div>
        <div class="goods-name">{{ goods.name }}</div>
        <div class="goods-description">{{ goods.description }}</div>
      </div>
    </div>
    <van-action-bar>
      <van-action-bar-button type="danger" @click="addAndGotoCart" text="下单" />
    </van-action-bar>
  </div>
</template>

<script>
import { reactive, onMounted, computed, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { getStorage } from '@/common/js/utils'
import { queryGoods, addToCart } from '@/service/axios-services'
import sHeader from '@/components/MyHeader'
import { Toast } from 'vant'
export default {
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const state = reactive({
      goods: ''
    })

    onMounted(async () => {
      const { id } = route.params
      const { data } = await queryGoods(id)
      state.goods = data
      store.dispatch('updateCart')
    })

    const goBack = () => {
      router.go(-1)
    }

    const goTo = () => {
      router.push({ path: '/cart' })
    }

    const doAddToCart = async () => {
      const token = getStorage('token')
      if (!token) {
        router.push({ path: '/login' })
        return
      }

      const { code } = await addToCart({ goodsId: state.goods.id })
      if (code == 0) {
        store.dispatch('updateCart')
        Toast.success('已加入购物车')
      }
    }

    const addAndGotoCart = async () => {
      const token = getStorage('token')
      if (!token) {
        router.push({ path: '/login' })
        return
      }

      const { code } = await addToCart({ goodsId: state.goods.id })
      if (code == 0) {
        store.dispatch('updateCart')
        router.push({ path: '/cart' })
      }
    }

    const count = computed(() => {
      return store.state.cartItemCount
    })

    return {
      ...toRefs(state),
      goBack,
      goTo,
      doAddToCart,
      addAndGotoCart,
      count
    }
  },
  components: {
    sHeader
  }
}
</script>

<style>
.goods-info {
  margin-top: 10px;
  padding: 0 10px;
  margin-bottom: 20px;
}
.goods-price {
  font-size: 18px;
  color: #ED9220;
}
.goods-name {
  margin-top: 10px;
  font-size: 18px;
}
.goods-description {
  margin-top: 10px;
  font-size: 16px;
  color:dimgrey;
  padding-bottom: 60px;
}
.common-img {
  height: auto;
  width: auto;
  max-width: 100%;
  max-height: 100%;
}
.van-action-bar-button--warning {
  background: linear-gradient(to right, #f688a4, #ED9220);
}
.van-action-bar-button--danger {
  background: linear-gradient(to right, #ED9220, #f688a4);
}
</style>